/**
 * 
 */
package com.qq.spirit;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import com.qq.spirit.inter.AbstractXmlActionAfterRequest;
import com.qq.spirit.inter.TaskUnit;
import com.qq.spirit.model.UserData;
import com.qq.spirit.model.XmlDataUtil;
import com.qq.spirit.model.XmlNodeData;

/**
 * 贸易任务
 * 
 * @author beedoorwei
 * 
 */
public class StockTask extends TaskUnit
{

	public StockTask()
	{
		this.taskDesc = "贸易任务";
	}

	@Override
	public void doTask()
	{
		try
		{
			if (!GameUserInfoUtil.getIsUserLoadSuc())
			{
				TaskManager.addTask(this, 10);
			} else
			{
				Iterator<Integer> ite = GameUserInfoUtil.userIte();
				while (ite.hasNext())
				{
					Integer gid = ite.next();
					UserData u = GameUserInfoUtil.getUser(gid);
					if (u.getConfigValue("openStock", "0").equals("1"))
					{
						TaskManager.addTask(new Stock(gid));
					}
				}
			}
		} catch (Exception e)
		{
			LoggerUtil.error(0, e);
		}
	}

	/**
	 * 贸易任务
	 * 
	 * @author Administrator
	 * 
	 */
	class Stock extends TaskUnit
	{
		public Stock(Integer gid)
		{
			this.gid = gid;
		}

		public void doTask()
		{
			try
			{
				if (isInStockTime())
				{
					UserData u = GameUserInfoUtil.getUser(gid);
					if (u.getUserState() == UserState.LOGIN_GAME)
					{
						HttpUtil.doGet(gid, GameConstants.STOCK_QUERY_URL, new PreStockAction(gid));
					} else
					{
						// 添加登录任务先
						TaskManager.addTask(new LoginTask(gid, this));
					}
				}
			} catch (Exception e)
			{
				LoggerUtil.error(0, e);
			}
		}
	}

	/**
	 * 是否是贸易时间
	 * 
	 * @return
	 */
	private boolean isInStockTime()
	{
		int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
		if (hour >= 8 && hour <= 23)
		{
			return true;
		}
		return false;
	}

	/**
	 * 贸易前查询
	 * 
	 * @author Administrator
	 * 
	 */
	class PreStockAction extends AbstractXmlActionAfterRequest
	{
		public PreStockAction(Integer gid)
		{
			super();
			this.gid = gid;
			this.taskUnit = new Stock(gid);
		}

		@Override
		public void doCall(List<Header> headerList, XmlNodeData stockInfo)
		{
			UserData u = GameUserInfoUtil.getUser(gid);
			// 目前只做苹果和铁矿生意，别的不做
			int currentpositon = GameUtil.convertInt(XmlDataUtil.getNodeData(stockInfo, "results.currentpositon"));
			int postion = GameUtil.convertInt(XmlDataUtil.getNodeData(stockInfo, "results.postion"));
			for (int i = 1; i <= 7; i++)
			{
				XmlNodeData xd = XmlDataUtil.getNodeInfo(stockInfo, "results.g" + i);
				int currPrize = GameUtil.convertInt(XmlDataUtil.getNodeData(xd, "price"));// 当前价格
				int selPrize = GameUtil.convertInt(u.getConfigValue("stockSell_" + i, "1000000"), 1000000);
				int buyPrize = GameUtil.convertInt(u.getConfigValue("stockBuy_" + i, "0"), 0);
				// 优先处理卖
				if (currPrize >= selPrize)
				{
					int storage = GameUtil.convertInt(XmlDataUtil.getNodeData(xd, "storage"));// 目前持有量
					if (storage > 0)
					{
						int num = GameUtil.convertInt(XmlDataUtil.getNodeData(xd, "num"));// 单位容量
						int ocd = GameUtil.convertInt(XmlDataUtil.getNodeData(xd, "cd"));// 单位耗时
						int totalTime = ocd * (storage / num) * 6;
						doStock(StockType.SELL, i, totalTime);
						break;
					}
				} else if (currPrize <= buyPrize)
				{
					int canBuy = postion - currentpositon;
					if (canBuy > 0)
					{
						int num = GameUtil.convertInt(XmlDataUtil.getNodeData(xd, "num"));// 单位容量
						int ocd = GameUtil.convertInt(XmlDataUtil.getNodeData(xd, "cd"));// 单位耗时
						int totalTime = ocd * (canBuy / num) * 60;
						doStock(StockType.BUY, i, totalTime);
						break;
					}
				}
			}

		}

		/**
		 * @param num
		 * @param tradeType
		 * @param goodId
		 * @param time
		 */
		public void doStock(StockType tradeType, int goodId, int aftertime)
		{
			List<BasicNameValuePair> nvpList = new ArrayList<BasicNameValuePair>();
			nvpList.add(new BasicNameValuePair("num", "99"));
			nvpList.add(new BasicNameValuePair("tradeType", tradeType.value + ""));
			nvpList.add(new BasicNameValuePair("goodId", goodId + ""));

			LoggerUtil.info(gid, tradeType.desc + getGoodName(goodId) + "," + aftertime + "秒后结束");
			HttpUtil.doPost(gid, GameConstants.STOCK_TRADE_URL, nvpList, new StockResultAction(gid, aftertime));
		}
	}

	/**
	 * @param goodId
	 * @return
	 */
	private String getGoodName(int goodId)
	{
		switch (goodId)
		{
		case 1:
			return "绿豆";
		case 2:
			return "苹果";
		case 3:
			return "木材";
		case 4:
			return "铁矿";
		case 5:
			return "黄金";
		case 6:
			return "珍珠";
		case 7:
			return "钻石";
		}
		return "";
	}

	class StockResultAction extends AbstractXmlActionAfterRequest
	{
		int time = 0;

		public StockResultAction(int gid, int time)
		{
			super();
			this.gid = gid;
			this.taskUnit = new Stock(gid);
			this.time = time;
		}

		@Override
		public void doCall(List<Header> headerList, XmlNodeData stockInfo)
		{
			LoggerUtil.info(gid, "贸易执行成功");
			TaskManager.addTask(taskUnit, 30 * 60);

		}
	}

}

enum StockType {
	BUY(0, "买入"), SELL(1, "卖出");
	public int value;
	public String desc;

	private StockType(int value, String desc)
	{
		this.value = value;
		this.desc = desc;
	}
}
